/**
 * CallItem
 */

 import React,{Component} from "react";
 import Validator from "../../../../../utils/validator/Validator";
 
 class CallItem extends Component{
    constructor(props) {
        super(props);
        this.state = {             
            number: ""
        };
    }
    componentWillMount(){
        const {data} = this.props;
        this.number = data.action.number || "";
        this.setState({
            number: this.number
        });
    }
    componentWillUnMount(){
        this.saveNumber();
    }
    checkValidate(){
        var validator = Validator();

        validator.addRule($(this.refs.phone), [{
            validator: "empty",
            error: $._('tel number can not be empty')
        }, {
            validator: "templatePhone",
            error: $._('Please enter a valid phone number')
        }]);

        var errors = validator.execute();
        if (errors){
            alert(errors);
            return false;
        }
        return true;
    }
    handleOnChangeNumber(e){
        var element = $(e.target || e.srcElement);
        this.number = element.val();
        this.setState({
            number: this.number
        });
    }
    saveNumber(){
        if (this.checkValidate()){
            const {data: widget,updateWidget,setState} = this.props;
            widget.action.number = this.number;

            setState({selectedWidget: widget});
            updateWidget(widget);
        }
    }
    render(){
        const {data} = this.props;
        return (
            <input disabled={data.readOnly} ref="phone" onBlur={() => this.saveNumber()} onChange={(e) => this.handleOnChangeNumber(e)} name="call" type="text" value={ this.state.number } />
        )
    }
 }

 module.exports = CallItem;
